package com.xdf.wxbebarrel.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Component
public class RestTemplateUtils {
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送 post 请求，请求头类型 application/json; charset=UTF-8，即要求服务端是 RequestBody 形式接受参数
     * @param url 请求的URL
     * @param reqObject 请求体参数，要求是实体类对象或者Map对象
     * @param responseType 返回数据的类型，例如：String.class,JsonResult.class
     * @return 返回请求响应来的结果 - 字符串类型
     * @throws JsonProcessingException
     */
    public <T> T doPostJson(String url, Object reqObject, Class<T> responseType) throws JsonProcessingException {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        ObjectMapper mapper = new ObjectMapper();
        ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
        String reqObjString = ow.writeValueAsString(reqObject);

        HttpEntity<String> httpEntity = new HttpEntity<String>(reqObjString, headers);
        T str = restTemplate.postForObject(url, httpEntity, responseType);
        return str;
    }

    /**
     * 使用 restTemplate 请求 get
     * @param url get请求url
     * @param params Map<String,Object> 类型的参数，会自动将参数拼接到 url 后面
     * @param responseType 返回的数据类型
     * @return
     * @param <T>
     */
    public <T> T doGet(String url, Map<String,Object> params, Class<T> responseType){
        return restTemplate.getForObject(url, responseType, params);
    }

    public <T> T doGet(String url, Class<T> responseType){
        return restTemplate.getForObject(url, responseType);
    }

}
